/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uy.edu.ort.as.cliente.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class UtilEncriptador {
    Cipher ecipher;
    Cipher dcipher;
    String textoclave = "claveencriptacion";

    UtilEncriptador() 
            throws 
            NoSuchAlgorithmException, 
            InvalidKeySpecException, 
            NoSuchPaddingException, 
            InvalidKeyException, 
            InvalidAlgorithmParameterException {

        byte[] salt = {
            (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
            (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
        };

        int contadorIteraciones = 19;

        KeySpec keySpec = new PBEKeySpec(textoclave.toCharArray(), salt, contadorIteraciones);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());

        AlgorithmParameterSpec param_spec = new PBEParameterSpec(salt, contadorIteraciones);

        ecipher.init(Cipher.ENCRYPT_MODE, key, param_spec);
        dcipher.init(Cipher.DECRYPT_MODE, key, param_spec);
    }

    public String encriptar(String cadena) 
            throws 
            UnsupportedEncodingException, 
            IllegalBlockSizeException, 
            BadPaddingException {
        byte[] utf8 = cadena.getBytes("UTF8");

        byte[] encoder = ecipher.doFinal(utf8);

        return new sun.misc.BASE64Encoder().encode(encoder);
    }
    
    public String desencriptar(String cadena) 
            throws 
            IOException, 
            IllegalBlockSizeException, 
            BadPaddingException {
        byte[] decoder = new sun.misc.BASE64Decoder().decodeBuffer(cadena);

        byte[] utf8 = dcipher.doFinal(decoder);

        return new String(utf8, "UTF8");
    }
}
